/*
 * Created on Nov 26, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.hermeneute.fsa.editors;

import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.hermeneute.fsa.FSTAbstractReader;
import com.hermeneute.fsa.FSTSequentialTransducer;

/**
 * @author mauceri
 * 
 * Preferences - Java - Code Style - Code Templates
 */

public class FSTReader extends FSTAbstractReader {


	public FSTReader(FSTSequentialTransducer st, Reader in) {
		super(st,in);
	}

	public FSTReader(FSTSequentialTransducer st, Reader in, int type) {
		super(st,in,type);
	}
	protected int evalTodo(int initialPosIn, int initialPositionOut) throws Exception {
		String todo = lastEpsilonProduction;
		char [] tmpBuffer = new char [buffer.length];

		int posIn = initialPosIn;
		int posOut = initialPositionOut;
		int lastEnd = 0;
		//System.out.println(todo);
		while (!todo.equals("")) {
			Pattern p = Pattern.compile("\\$([\\d]+)");
			Matcher matcher = p.matcher(todo);
			matcher.find();
			int posToReplace = Integer.valueOf(matcher.group(1)).intValue() - 1;
			
			EpsilonMarker marker = (EpsilonMarker) marks.elementAt(posToReplace);

			todo = todo.replaceFirst("^\\$([\\d]+) *", "");
			marker.replacePattern = getReplacePattern(todo);
			todo = todo.substring(marker.replacePattern.length());
			if (!todo.equals("") && todo.charAt(0) == ',') todo = todo.substring(1);
			marker.replacePattern = marker.replacePattern.replaceAll("\\\\,", ",");
		}

		for (int i = 0; i <marks.size(); i++) {
			EpsilonMarker marker = (EpsilonMarker) marks.elementAt(i);
			if (marker.replacePattern != null){
				//System.out.println("rep");
				for (int j = posIn; j < marker.start; j++) {
					writeOut(buffer[j], posOut + j - posIn);
					//System.out.print(buffer[j]);
				}
				//System.out.println("first: "+marker.replacePattern);
				if (posIn < marker.start)
					posOut += marker.start - posIn;
				posIn = marker.end;
				lastEnd = marker.end;
				int posTmpBuffer = expandReplacePattern(
							marker.replacePattern.toCharArray(),
							tmpBuffer);
				for (int j = 0; j < posTmpBuffer; j++) {
					writeOut(tmpBuffer[j], posOut + j);
				}
				posOut += posTmpBuffer;
			}
		}
		
		currentPosition = lastEnd;
		return posOut;
	}
}